#include "List.h"
#define _CRT_SECURE_NO_WARNINGS 1

void ListInsert(LTNode* plist, LTNode* pos, LTDataType data)
{
	assert(plist);
	assert(pos);
	LTNode* newnode = BuyListNode(data);
	LTNode* posprev = pos->prev;
	posprev->next = newnode;
	newnode->prev = posprev;
	newnode->next = pos;
	pos->prev = newnode;
}

LTNode* ListFind(LTNode* plist, LTDataType data)
{
	assert(plist);
	LTNode* cur = plist->next;
	while (cur != plist)
	{
		if (data == cur->data)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListErase(LTNode* plist, LTNode* pos)
{
	assert(plist);
	assert(plist->next != plist);
	LTNode* posnext = pos->next;
	LTNode* posprev = pos->prev;
	posnext->prev = posprev;
	posprev->next = posnext;
	free(pos);
}

LTNode* ListInit()
{
	LTNode* phead = (LTNode*)malloc(sizeof(LTNode));
	if (phead == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

LTNode* BuyListNode(LTDataType data)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	newnode->data = data;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

void ListPushFront(LTNode* plist, LTDataType data)
{
	ListInsert(plist, plist->next, data);
}

void ListPushBack(LTNode* plist, LTDataType data)
{
	ListInsert(plist, plist, data);
}

void ListPopFront(LTNode* plist)
{
	ListErase(plist, plist->next);
}

void ListPopBack(LTNode* plist)
{
	ListErase(plist, plist->prev);
}

void ListDestory(LTNode* plist)
{
	assert(plist);
	LTNode* cur = plist->next;
	while (cur != plist)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(plist);
}

void ListPrint(LTNode* plist)
{
	assert(plist);
	LTNode* cur = plist->next;
	if (cur == plist)
	{
		printf("NULL");
	}
	while (cur != plist)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}
